package cn.net.yugu.doraemon.api.common.response;

import cn.net.yugu.doraemon.api.common.enums.CommonResultCode;
import cn.net.yugu.doraemon.api.common.enums.IErrorCode;
import lombok.Data;

import java.io.Serializable;

/**
 * @description:
 * @author: wanghongli
 * @create: 2022-11-29 19:34:13
 */
@Data
@SuppressWarnings("unchecked")
public class DataResult<T> implements Serializable {
    /**
     * 结果 code.
     */
    private Integer code;
    /**
     * 返回数据.
     */
    private T data;
    /**
     * 非成功接口报错消息.
     */
    private String message;

    public DataResult() {
    }

    public DataResult(T data, Integer code, String message) {
        this.data = data;
        this.code = code;
        this.message = message;
    }

    public static <T> DataResult<T> success() {
        return successWithData(null);
    }

    public static <T> DataResult<T> successWithData(T data) {
        return new DataResult<T>(data, CommonResultCode.SUCCESS.getCode(), null);
    }

    public static <T> DataResult<T> failWithMessage(String message) {
        return new DataResult<T>(null, CommonResultCode.FAIL.getCode(), message);
    }

    public static <T>DataResult<T> failWithMessage(Integer code, String message) {
        return new DataResult<T>(null, code, message);
    }

    public static <T>DataResult<T> failWithError(IErrorCode errorCode) {
        return new DataResult<>(null, errorCode.getCode(), errorCode.getMessage());
    }

    public boolean isSuccess() {
        return code!= null && code == CommonResultCode.SUCCESS.getCode();
    }

    public boolean isFail() {
        return !isSuccess();
    }
}
